import json , os , uuid
from utils.loggingConfig import get_logger
from fastapi import APIRouter , Request
from fastapi.responses import StreamingResponse
from service.neuttsAirService import neuttsAirService

fapp = None
router = APIRouter()

root_path = os.path.abspath(__file__)
for i in range(2):
    root_path = os.path.dirname(root_path)

outputsDir = os.path.join(root_path , 'outputs/')

logger = get_logger('')

# @router.post("/experience/neuttsAir", description="体验neutts-air-main 模型")
# 硅基流动的标准接口
@router.post("/v1/audio/speech", description="体验neutts-air-main 模型")
async def neuttsAir(param: dict , request:Request):
    logger.info("######### neuttsAir")
    rt = await request.body()
    rt = rt.decode('utf-8')
    param = json.loads(rt)
    input_text = param.get('input' , 'Hello, how are you today?')
    ref_type = param.get('voice', 'dave')
    modelname = param.get('model', 'neuphonic/neutts-air')
    req_id = uuid.uuid1()
    wav_path = os.path.join(outputsDir , f'{req_id}-test.wav')

    await neuttsAirService(req_id , input_text , ref_type)

    # wav_path = os.path.join(outputsDir, 'dave.wav')

    # 定义文件读取生成器（流式读取）
    def file_generator():
        with open(wav_path, "rb") as f:
            while chunk := f.read(1024 * 1024):  # 每次读取1MB
                yield chunk

    # 流式返回
    return StreamingResponse(
        content=file_generator(),
        media_type="audio/wav",
        headers={"Content-Disposition": 'attachment; filename="stream_output.wav"'}
    )
